package org.nobody.mallb2c.mallseckill.scheduled;

import lombok.extern.slf4j.Slf4j;
import org.nobody.mallb2c.mallseckill.service.SeckillService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author 3489309323@qq.com
 * @create 2020-09-28-13:45
 *
 * 秒杀商品的定时上架:
 *
 * 每天晚上3点,上架最近三天需要秒杀的商品
 * + 当天 00:00:00 - 23:59:59
 * + 明天 00:00:00 - 23:59:59
 * + 后天 00:00:00 - 23:59:59
 *
 */

@Slf4j
@Service
public class SeckillSkuScheduled {
  @Autowired
  SeckillService seckillService;

  @Autowired
  RedissonClient redissonClient;

  private final String upload_lock = "seckill:upload:lock";

  //@Scheduled(cron = "0 0 3 * * ?")
  @Scheduled(cron = "*/5 * * * * ?")
  public void uploadSeckillSkuLatest3Days(){
    //1、重复上架无需处理
    log.info("上架秒杀的商品信息");
    RLock lock = redissonClient.getLock(upload_lock); //防止分布式下 多台服务器同时执行该定时任务
    lock.lock(10, TimeUnit.SECONDS);
    try {
      seckillService.uploadSeckillSkuLatest3Days();
    }finally {
      lock.unlock();
    }
  }
}
